{% extends "base.html" %}

{% block title %}盘点任务管理{% endblock %}

{% block content %}

    <div class="container mt-4">
        <h3 class="mb-4">盘点任务管理         
            {% if session.role == 'super_user' %}
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#createTaskModal">
                <i class="fas fa-plus me-1"></i>新任务 
            </button>
            {% endif %}     
        </h3>
    
        <!-- Enhanced Task Status Panel -->
        <div class="card mt-4 shadow-sm" id="taskPanel" style="display: none;">
            <div class="card-header py-3">
                <h4 class="mb-0"><i class="fas fa-tasks me-2"></i>当前任务状态</h4>
            </div>
            <div class="card-body p-4">
                <div class="row">
                    <div class="col-md-8">
                        <table class="table table-borderless">
                            <tbody>
                                <tr>
                                    <td class="text-muted " style="width: 80px">任务ID</td>
                                    <td><span id="taskId" class="badge bg-dark fs-6">-</span></td>
                          
                                    <td class="text-muted ">操作类型</td>
                                    <td><span id="action" class="badge bg-info fs-6">-</span></td>
                         
                                    <td class="text-muted ">描述</td>
                                    <td><span id="description" class="badge bg-success fs-6">-</span></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="col-md-4 d-flex align-items-center justify-content-center">
                        <div class="text-center">
                            <div class="text-muted  mb-2">当前状态</div>
                            <div id="taskStatus" style="font-size: 1.5em; font-weight: bold;">
                                <span class="text-muted">准备就绪</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
       
            <div class="card-body">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th width="30%">标记点</th>
                            <th>操作类型</th>
                            <th>描述</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <style>
                        .marker-cell {
                            white-space: normal;
                            word-break: break-word;
                            max-width: 200px;
                        }
                    </style>
                    <tbody id="tasksTable">
                        <!-- Tasks will be populated here -->
                    </tbody>
                </table>
                
                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center">
                        <li class="page-item">
                            <a class="page-link" href="#" id="prevPage">上一页</a>
                        </li>
                        <li class="page-item">
                            <span class="page-link" id="currentPage">1</span>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="#" id="nextPage">下一页</a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
    </div>

    <!-- Create Task Modal -->
    <div class="modal fade" id="createTaskModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">创建新任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="taskForm">
                        <div class="mb-3">
                            <label for="marker" class="form-label">标记点</label>
                            <textarea class="form-control" id="marker" rows="5"
                                   placeholder="示例: M1,M2,CD"></textarea>
                            <div class="form-text text-muted">
                                <div class="alert alert-info p-2 mt-2 mb-0">
                                    <i class="fas fa-info-circle me-2"></i>标记点填写要求：
                                    <ul class="mb-0 ps-3 mt-1">
                                        <li>使用英文逗号分隔多个点位</li>
                                        <li>点位名称必须与地图系统中的点位名称一致</li>
                                        <li>至少需要输入两个点位</li>
                                        <li>路线必须以充电点(CD)结束</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="action" class="form-label">操作类型</label>
                            <select class="form-select" id="action">
                                <option value="0">拍照</option>
                                <option value="1">录像</option>
                                <option value="99">仅是移动</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">描述</label>
                            <textarea class="form-control" id="description" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="createTask()">创建</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Task Modal -->
    <div class="modal fade" id="editTaskModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editTaskForm">
                        <input type="hidden" id="editTaskId">
                        <div class="mb-3">
                            <label for="editMarker" class="form-label">标记点</label>
                            <textarea class="form-control" id="editMarker" rows="2"
                                   placeholder="示例: M1,M2,CD"></textarea>
                            <div class="form-text text-muted">
                                <div class="alert alert-info p-2 mt-2 mb-0">
                                    <i class="fas fa-info-circle me-2"></i>标记点填写要求：
                                    <ul class="mb-0 ps-3 mt-1">
                                        <li>使用英文逗号分隔多个点位</li>
                                        <li>点位名称必须与地图系统中的点位名称一致</li>
                                        <li>至少需要输入两个点位</li>
                                        <li>路线必须以充电点(CD)结束</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="editAction" class="form-label">操作类型</label>
                            <select class="form-select" id="editAction">
                                <option value="0">拍照</option>
                                <option value="1">录像</option>
                                <option value="99">仅是移动</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="editDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="editDescription" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveTaskBtn">保存</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    <script src="{{ url_for('static', filename='js/main.js') }}"></script>
    <script>
        // Load tasks when page loads
        document.addEventListener('DOMContentLoaded', loadTasks);

        // Save edited task
        document.getElementById('saveTaskBtn').addEventListener('click', saveTask);

        let currentPage = 1;
        const pageSize = 5;
        
         // <td>${task.description}</td>
        function loadTasks() {
            fetch(`/api/tasks?page=${currentPage}&size=${pageSize}`)
                .then(response => response.json())
                .then(data => {
                    const tableBody = document.getElementById('tasksTable');
                    tableBody.innerHTML = '';
                    document.getElementById('currentPage').textContent = currentPage;
                    
                    data.data.forEach(task => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${task.task_id}</td>
                            <td class="marker-cell">${task.marker}</td>
                            <td>${getActionText(task.action)}</td>
                            <td>${task.description}</td>
                            <td>${task.create_at ? task.create_at.slice(0,10) : ''}</td>
             
                            <td>
                                {% if session.role == 'super_user' %}
                                    <button class="btn btn-lg btn-primary" onclick="editTask(${task.task_id})">编辑</button>
                                    <button class="btn btn-lg btn-danger" onclick="deleteTask(${task.task_id})">删除</button>
                                {% endif %}                                
                                
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                <button class="btn btn-lg btn-success" onclick="runTask(${task.task_id})">执行 <i class="fa fa-paper-plane" aria-hidden="true"></i>
</button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                });
        }
        
        document.getElementById('prevPage').addEventListener('click', (e) => {
            e.preventDefault();
            if (currentPage > 1) {
                currentPage--;
                loadTasks();
            }
        });

        document.getElementById('nextPage').addEventListener('click', (e) => {
            e.preventDefault();
            currentPage++;
            loadTasks();
        });

        function getActionText(action) {
            if (action === 0 || action === "0") return '拍照';
            if (action === 1 || action === "1") return '录像';
            if (action === 99 || action === "99") return '仅是移动';
            return '未知';
        }

        function getStatusText(status) {
            switch (status) {
                case 1:
                case '1':
                    return '进行中';
                case 2:
                case '2':
                    return '已完成';
                case 3:
                case '3':
                    return '部分完成';
                case 4:
                case '4':
                    return '执行失败';
                default:
                    return '准备就绪';
            }
        }


        function validateMarker(marker) {
            if (!marker) {
                alert('请输入标记点');
                return false;
            }

            // 检查是否包含中文逗号
            if (marker.includes('，')) {
                alert('请使用英文逗号(,)分隔点位，不要使用中文逗号(，)');
                return false;
            }

            const points = marker.split(',').map(p => p.trim());
            
            if (points.length < 2) {
                alert('至少需要输入两个点位');
                return false;
            }

            if (points[points.length - 1] !== 'CD') {
                alert('路线必须以充电点(CD)结束');
                return false;
            }

            return true;
        }

        function createTask() {
            const form = document.getElementById('taskForm');
            const markerInput = form.querySelector('#marker');
            
            if (!validateMarker(markerInput.value)) {
                return;
            }

            const actionSelect = form.querySelector('#action');
            const descriptionTextarea = form.querySelector('#description');
            
            const taskData = {
                marker: form.querySelector('#marker').value,
                action: actionSelect ? parseInt(actionSelect.value) : 0,
                description: descriptionTextarea ? descriptionTextarea.value : ''
            };
            
            console.log('Form elements:', {
                actionSelect: actionSelect,
                descriptionTextarea: descriptionTextarea
            });
            console.log('Submitting task data:', taskData);

            fetch('/tasks', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(taskData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 'OK') {
                    // Close modal and refresh task list
                    const modal = bootstrap.Modal.getInstance(document.getElementById('createTaskModal'));
                    modal.hide();
                    loadTasks();
                    
                    // Clear form
                    document.getElementById('taskForm').reset();
                } else {
                    alert('创建任务失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('创建任务时出错: ' + error.message);
            });
        }
    


        function editTask(taskId) {
            fetch(`/api/tasks/${taskId}`)
                .then(response => response.json())
                .then(task => {
                    document.getElementById('editTaskId').value = taskId;
                    document.getElementById('editMarker').value = task.marker;
                    document.getElementById('editAction').value = task.action;
                    document.getElementById('editDescription').value = task.description;
                    
                    const modal = new bootstrap.Modal(document.getElementById('editTaskModal'));
                    modal.show();
                });
        }

        function saveTask() {
            const taskId = document.getElementById('editTaskId').value;
            const markerValue = document.getElementById('editMarker').value;
            
            if (!validateMarker(markerValue)) {
                return;
            }

            const taskData = {
                marker: markerValue,
                action: parseInt(document.getElementById('editAction').value),
                description: document.getElementById('editDescription').value
            };

            fetch(`/api/tasks/${taskId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(taskData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'OK') {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('editTaskModal'));
                    modal.hide();
                    loadTasks();
                }
            });
        }

        function deleteTask(taskId) {
            if (confirm('确定要删除这个任务吗？')) {
                fetch(`/api/tasks/${taskId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'OK') {
                        loadTasks();
                    }
                });
            }
        }

        // 在任务状态面板赋值时，action显示支持“仅是移动”
        function showTaskPanel(task) {
            document.getElementById('taskPanel').style.display = '';
            document.getElementById('taskId').textContent = task.task_id;
            document.getElementById('action').textContent = getActionText(task.action);
            document.getElementById('description').textContent = task.description;
            document.getElementById('taskStatus').innerHTML = `<span>${getStatusText(task.status)}</span>`;
        }

        // 在runTask等需要弹出当前任务状态面板的地方调用 showTaskPanel(task)
        // function pollTaskStatus(taskId) {
        //     const interval = setInterval(() => {
        //         fetch(`/api/tasks/${taskId}`)
        //             .then(response => response.json())
        //             .then(task => {
        //                 if (task.status && task.status !== 1) { // 1=进行中
        //                     clearInterval(interval);
        //                     updateTaskStatus(task);
        //                 }
        //             });
        //     }, 1000);
        // }

        // function updateTaskStatus(task) {
        //     document.getElementById('taskStatus').innerHTML = 
        //         `<span>${getStatusText(task.status)}</span>`;
        // }


        function pollTaskStatus(taskId) {
            let attempts = 0;
            const maxAttempts = 60; // 最多等待60秒
            
            const interval = setInterval(() => {
                attempts++;
                
                fetch(`/api/tasks/${taskId}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.json();
                    })
                    .then(task => {
                        // 更新当前状态显示
                        updateTaskStatus(task);
                        
                        // 检查是否需要停止轮询
                        if (task.status && task.status !== 1) { // 1=进行中
                            clearInterval(interval);
                            console.log('Task completed with status:', task.status);
                        }
                    })
                    .catch(error => {
                        console.error('Error polling task status:', error);
                        clearInterval(interval);
                        // 显示错误状态
                        document.getElementById('taskStatus').innerHTML = 
                            `<span class="text-danger">状态更新失败</span>`;
                    });
                    
                // 超时处理
                if (attempts >= maxAttempts) {
                    clearInterval(interval);
                    document.getElementById('taskStatus').innerHTML = 
                        `<span class="text-warning">状态更新超时</span>`;
                }
            }, 1000);
        }

        function updateTaskStatus(task) {
            const statusElement = document.getElementById('taskStatus');
            const statusText = getStatusText(task.status);
            
            // 根据不同状态显示不同样式
            let statusClass = 'text-primary';
            if (task.status === 2) statusClass = 'text-success'; // 完成
            if (task.status === 3) statusClass = 'text-warning'; // 部分完成
            if (task.status === 4) statusClass = 'text-danger';  // 失败

            statusElement.innerHTML = `<span class="${statusClass}">${statusText}</span>`;
        }




        function runTask(taskId) {
            fetch(`/api/tasks/${taskId}`)
                .then(response => response.json())
                .then(task => {
                    // 创建一个新的任务对象，将状态设置为初始状态
                    const initialTask = {
                        ...task,
                        status: 0  // 0 表示准备就绪
                    };
                    showTaskPanel(initialTask);
                    fetch(`/api/tasks/${taskId}/run`, { method: 'POST' })
                        .then(() => pollTaskStatus(taskId));
                });
        }
    </script>
{% endblock %}
